<template>
  <Section>
    <GapedColumn>
      <PageHeader title="索引管理" icon="coin">
        <template #extra>
          <!-- Additional header content if needed -->
        </template>
      </PageHeader>
      <search-input @search="handleSearch" />

      <AddButton buttonText="新增索引" @click="addIndexDialog.show()" />
      <div
        v-for="index in filteredIndices"
        :key="index.name"
        class="index-section"
      >
        <GapedRow gap="large" width="100%">
          <h4>{{ index.name }}</h4>
          <GapedRow>
            <el-button type="primary" @click="handleEdit(index)">
              编辑
            </el-button>
            <el-button type="primary" @click="initEsMapping(index)">
              写入索引
            </el-button>
            <el-button type="primary" @click="handleEdit(index)">
              重建索引
            </el-button>
          </GapedRow>
        </GapedRow>
        <el-table :data="index.data" border style="width: 100%">
          <!-- 表格列定义 -->
          <el-table-column prop="field" label="字段名" />
          <el-table-column prop="type" label="类型" />
          <el-table-column prop="description" label="描述" />
        </el-table>
      </div>

      <AddIndexDialog
        ref="addIndexDialog"
        :confirmCallback="handleAddIndex"
        @closed="handleClose"
      />
    </GapedColumn>
  </Section>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Section, GapedColumn, GapedRow } from '@/core/components'
import { AddButton } from '@/components'
import { AddIndexDialog, SearchInput } from '@/components/es'
import useApi from '@/core/apiStore'
import { showSuccessSaveMessage } from '@/utils'
import { reduce } from 'lodash'

interface PropertyMapping {
  field_type: string
  analyzer?: string
  format?: string
  index?: boolean
  fields?: Record<string, PropertyMapping>
}

interface TypeMapping {
  name: string
  properties: Record<string, PropertyMapping>
  dynamic?: boolean
}

interface IndexDisplayData {
  name: string
  data: Array<{
    field: string
    type: string
    description?: string
  }>
}

const apiStore = useApi()
const addIndexDialog = ref()

const indices = ref<IndexDisplayData[]>([])

const handleEdit = (indexObj: any) => {
  const result = {
    ...indexObj,
    properties: reduce(
      indexObj.data,
      (acc, item) => {
        return {
          ...acc,
          [item.field]: { ...item, fieldName: item.field },
        }
      },
      {}
    ),
  }
  addIndexDialog.value.show(result)
}


const initEsMapping = async (indexObj: any)=>{
  const { name } = indexObj

  const result = await apiStore.initEsMapping({name})
  console.log("es-init-result", result);
  showSuccessSaveMessage('索引初始化')
}

const transformPropertiesToDisplayData = (
  properties: Record<string, PropertyMapping>,
  parentField = ''
): Array<{
  field: string
  type: string
  description?: string
}> => {
  const result: Array<{
    field: string
    type: string
    description?: string
  }> = []

  for (const [field, mapping] of Object.entries(properties)) {
    const fullFieldName = parentField ? `${parentField}.${field}` : field
    result.push({
      field: fullFieldName,
      type: mapping.type,
      description: mapping.format || mapping.analyzer || undefined,
    })

    if (mapping.fields) {
      result.push(
        ...transformPropertiesToDisplayData(mapping.fields, fullFieldName)
      )
    }
  }

  return result
}

const reload = async () => {
  const { data } = await apiStore.getEsIndexes()
  indices.value = data.map((index: TypeMapping) => ({
    name: index.name,
    data: transformPropertiesToDisplayData(index.properties),
  }))
}
onMounted(async () => {
  await reload()
})

const handleAddIndex = async (indexData: any, isNew: boolean) => {
  console.log('索引数据:', indexData)
  if (isNew) {
    await apiStore.createEsIndex(indexData)
    showSuccessSaveMessage('新建索引')
  } else {
    await apiStore.editEsIndex(indexData)
    showSuccessSaveMessage('编辑索引')
  }
  return true
}

const searchQuery = ref('')

const filteredIndices = computed(() => {
  if (!searchQuery.value) return indices.value
  return indices.value.filter(index =>
    index.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

const handleSearch = (query: string) => {
  searchQuery.value = query
}

const handleClose = async (needUpdate: boolean) => {
  if (needUpdate) {
    await reload()
  }
}
</script>

<style scoped>
.es-index-management {
  padding: 20px;
}

.index-section {
  margin-bottom: 30px;
}

.index-section h3 {
  margin-bottom: 15px;
  color: #333;
}
</style>
